from django.utils.deprecation import MiddlewareMixin
from api.models import User
from django.http import JsonResponse
from aiops_backend import settings
import jwt


class AuthMiddleWare(MiddlewareMixin):

    def process_request(self, request):
        if request.path_info == "/login":
            return
        else:
            try:
                auth = request.META.get("HTTP_AUTHORIZATION", None)
                if auth is None:
                    # TODO: do sth to authorizate api called
                    return
                auth = auth.split(" ")
            except AttributeError:
                return JsonResponse({"error": "No authenticate header"}, status=401)
        if auth[0].lower() == "token":
            try:
                auth_dict = jwt.decode(auth[1], settings.SECRET_KEY, algorithms=["HS256"])
                id = auth_dict.get("data").get("id")
                user_object = User.objects.get(id=id)
                if not user_object:
                    return JsonResponse({"error": "User Didn't Exist!"}, status=401)
                request.user = user_object
            except jwt.ExpiredSignatureError:
                return JsonResponse({"error": "Token expired"}, status=401)
            except jwt.InvalidTokenError:
                return JsonResponse({"error": "Invalid token"}, status=401)
            except Exception as e:
                return JsonResponse({"error": str(e)}, status=401)
        else:
            return JsonResponse({"error": "Not support auth type"}, status=401)
